<template>
  <div class="app-container">
    <el-card style="height: 280px">
      <el-row :gutter="20">
        <el-col :span="8">
          <!--消费统计-->
          <el-card>
            <div slot="header">
              <span>消费统计</span>
            </div>
            <div id="memberConsumption"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <!--次数统计-->
          <el-card>
            <div slot="header">
              <span>充值/退费次数统计</span>
            </div>
            <div id="consumptionCount"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <!--次数统计-->
          <el-card>
            <div slot="header">
              <span>充值方式统计</span>
            </div>
            <div id="paymentCount"></div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
    <el-card>
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
        <el-form-item label="充值订单号" prop="id">
          <el-input v-model="queryParams.id" placeholder="充值订单号" clearable style="width: 240px;" size="mini"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="支付类型" prop="payType">
          <el-select v-model="queryParams.payType" placeholder="订单状态" clearable size="mini" style="width: 240px">
            <el-option v-for="dict in payTypeOptions" :key="dict.value" :label="dict.label" :value="+dict.value"/>
          </el-select>
        </el-form-item>

        <el-form-item label="订单状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="订单状态" clearable size="mini" style="width: 240px">
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="+dict.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="dateRange" size="mini" style="width: 240px" value-format="yyyy-MM-dd"
                          type="daterange"
                          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange" :height="tableHeight">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="充值订单号" width="200" align="center" prop="id"/>
        <el-table-column label="支付时间" align="center" prop="payTime" width="140" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.payTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="平台交易号" align="center" prop="payPlatformId" width="200" :show-overflow-tooltip="true"/>
        <el-table-column label="历史充值金额" align="center" prop="amount">
          <template slot-scope="scope">
            <span>{{ scope.row.amount }} 元</span>
          </template>
        </el-table-column>
        <el-table-column label="未退费金额" align="center" prop="restAmount">
          <template slot-scope="{row}">
            <span v-if="row.status == 5" style="color: red">{{ row.restAmount }} 元</span>
            <span v-else>{{ row.restAmount }} 元</span>
          </template>
        </el-table-column>
        <el-table-column label="交易类型" align="center" prop="payType">
          <template slot-scope="scope">
            <span v-if="scope.row.payType==0" style="color: red;font-weight: bolder">现金</span>
            <span v-if="scope.row.payType==1" style="color: #00afff;font-weight: bolder">支付宝</span>
            <span v-if="scope.row.payType==2" style="color: lawngreen;font-weight: bolder">微信</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" align="center" prop="status" :formatter="statusFormat"/>
        <el-table-column label="创建时间" align="center" prop="gmtCreate" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.gmtCreate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="170px">
          <template slot-scope="{row}">
            <el-dropdown class="handle-button" v-if="row.payType != undefined">
            <span class="el-dropdown-link">操作<i class="el-icon-arrow-down el-icon--right"/>
            </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleAlipayRefund(row)">
                  <el-button size="mini" type="text" icon="el-icon-coin"
                             v-hasPerm="['beauty:member:refund']"
                             v-if="row.payType == 1 && row.status== 1 ">支付宝全额退款
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleAlipayPartialRefund(row)">
                  <el-button size="mini" type="text" icon="el-icon-coin"
                             v-hasPerm="['beauty:member:refund']"
                             v-if="row.payType == 1 && (row.status== 1 || row.status == 5)">支付宝部分退款
                  </el-button>
                </el-dropdown-item>

                <el-dropdown-item @click.native="handleCashRefund(row)">
                  <el-button size="mini" type="text" icon="el-icon-coin"
                             v-hasPerm="['beauty:member:refund']"
                             v-if="row.payType == 0 && row.status== 1">现金全额退款
                  </el-button>
                </el-dropdown-item>
                <el-dropdown-item @click.native="handleCashPartialRefund(row)">
                  <el-button size="mini" type="text" icon="el-icon-coin"
                             v-hasPerm="['beauty:member:refund']"
                             v-if="row.payType == 0 &&(row.status== 1 || row.status == 5)">现金部分退款
                  </el-button>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page.sync="queryParams.current" :limit.sync="queryParams.size"
                  @pagination="getList"/>
    </el-card>

    <!--打开退款金额-->
    <el-dialog title="部分退款" :visible.sync="openAmount" center :close-on-click-modal="false"
               append-to-body width="30%">
      <div style="text-align:center">
      </div>
      <el-form ref="partialRefundForm" :model="partialRefundForm" :rules="partialRefundAmountRules">
        <el-form-item label="退款金额" prop="amount">
          <el-input v-model="partialRefundForm.amount" placeholder="请输入充值金额" clearable maxlength="6" minlength="1"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPartialRefund">确 定</el-button>
        <el-button @click="cancePartialRefund">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTopUpByMemberId } from '@a/beauty/topUp'
import { refundWithAlipay, refundWithCash } from '@a/beauty/member'
import { Chart } from '@antv/g2'
import { getConsumptionCount, getMemberConsumption, getPaymentCount } from '@a/beauty/statistical'

export default {
  name: 'Info',
  inject: ['reload'],
  components: {
    Chart
  },
  data() {
    return {
      // 0 现金 1 支付宝
      refundType: undefined,
      // 部分退款表单
      partialRefundForm: {},
      // 部分退款缓存使用
      refundRow: {},
      partialRefundAmountRules: {
        amount: [
          { required: true, message: '充值金额不能为空', trigger: 'blur' },
          {
            message: '退款金额格式不合法',
            trigger: 'blur',
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/
          }
        ]
      },
      // 打开部分退款窗口
      openAmount: false,
      tableHeight: window.innerHeight - 600,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      // 状态数据字典
      statusOptions: [],
      // 支付类型数据字典
      payTypeOptions: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        current: 1,
        size: 10,
        memberId: undefined,
        id: undefined,
        payType: undefined,
        status: undefined
      }
    }
  },
  created() {
    const memberId = this.$route.params && this.$route.params.memberId
    this.queryParams.memberId = memberId
    this.queryParams.id = this.$route.params && this.$route.params.topUpId
    this.getList()
    this.getDictItems('beauty_top_up_status').then(response => {
      this.statusOptions = response.data
    })
    this.getDictItems('beauty_top_up_pay_type').then(response => {
      this.payTypeOptions = response.data
      // console.log('this.payTypeOptions', this.payTypeOptions)
    })
    this.getMemberConsumption(memberId)
    this.getConsumptionCount(memberId)
    this.getPaymentCount(memberId)
  },
  methods: {
    // 统计客户的总消费金额(不包含退费的),退费金额
    getMemberConsumption(memberId) {
      // 统计客户的总消费金额(不包含退费的),退费金额
      getMemberConsumption(memberId).then(res => {
        const chart = new Chart({
          container: 'memberConsumption',
          autoFit: true,
          height: 200
        })
        chart.data(res.data)
        chart.tooltip({
          showMarkers: false,
          shared: true
        })
        chart.interval().position('name*value').color('name').adjust([
          {
            type: 'dodge',
            marginRatio: 0
          }
        ])
        chart.interaction('active-region')
        chart.render()
      })
    },
    getConsumptionCount(memberId) {
      // 充值 退费次数统计
      getConsumptionCount(memberId).then(res => {
        const chart = new Chart({
          container: 'consumptionCount',
          autoFit: true,
          height: 200
        })
        chart.data(res.data)
        chart.scale('value', {
          formatter: (val) => {
            return val
          }
        })
        chart.coordinate('theta', {
          radius: 0.75,
          innerRadius: 0.6
        })
        chart.tooltip({
          showTitle: false,
          showMarkers: false,
          itemTpl: '<li class="g2-tooltip-list-item"><span style="background-color:{color};" class="g2-tooltip-marker"></span>{name}: {value}</li>'
        })
        chart.interval().adjust('stack').position('value').color('name').label('value', (value) => {
          return {
            content: (data) => {
              return `${data.name}: ${data.value}`
            }
          }
        }).tooltip('name*value', (item, percent) => {
          return {
            name: item,
            value: percent
          }
        })
        chart.interaction('element-active')
        chart.render()
      })
    },
    getPaymentCount(memberId) {
      // 支付方式统计
      getPaymentCount(memberId).then(res => {
        const chart = new Chart({
          container: 'paymentCount',
          autoFit: true,
          height: 200
        })
        chart.data(res.data)
        chart.tooltip({
          showMarkers: false,
          shared: true
        })
        chart.interval().position('name*value').color('name').adjust([
          {
            type: 'dodge',
            marginRatio: 0
          }
        ])
        chart.interaction('active-region')
        chart.render()
      })

    },
    // 确认部分退款
    submitPartialRefund() {
      let row = this.refundRow
      switch (this.refundType) {
        // 现金
        case 0:
          this.invokeCashRefund(row.memberId, row.id, this.partialRefundForm.amount)
          this.refundRow = {}
          this.refundType = undefined
          this.openAmount = false
          break
        // 支付宝
        case 1:
          this.invokeAlipayRefund(row.memberId, row.id, this.partialRefundForm.amount)
          this.refundRow = {}
          this.refundType = undefined
          this.openAmount = false
          break
        default:
          break
      }
    },
    // 取消部分退款
    cancePartialRefund() {
      this.openAmount = false
      this.partialRefundForm = {}
      this.refundType = undefined
    },
    // 现金部分退款
    handleCashPartialRefund(row) {
      this.partialRefundForm = {}
      this.openAmount = true
      this.refundType = 0
      this.refundRow = { ...row }
    },
    // 支付宝部分退费
    handleAlipayPartialRefund(row) {
      this.partialRefundForm = {}
      this.openAmount = true
      this.refundType = 1
      this.refundRow = { ...row }
    },
    // 执行现金退款
    invokeCashRefund(memberId, topUpId, amount) {
      this.$confirm(`充值订单号${topUpId},确认要退款吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return refundWithCash(memberId, topUpId, amount)
      }).then(() => {
        // 刷新当前页面
        this.reload()
        this.msgNoticeSuccess('现金退费成功')
      })
    },
    // 现金全额退款
    handleCashRefund(row) {
      this.invokeCashRefund(row.memberId, row.id, row.amount)
    },
    // 执行支付宝退款
    invokeAlipayRefund(memberId, topUpId, amount) {
      this.$confirm(`充值订单号${topUpId},确认要退款吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return refundWithAlipay(memberId, topUpId, amount)
      }).then(() => {
        this.reload()
        this.msgNoticeSuccess('支付宝退费成功')
      })
    },
    //  支付宝全额退费
    handleAlipayRefund(row) {
      this.invokeAlipayRefund(row.memberId, row.id, row.amount)
    },
    /** 查询登录日志列表 */
    getList() {
      this.loading = true
      listTopUpByMemberId(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.list = response.data.records
          this.total = response.data.total
          this.loading = false
        }
      )
    },
    //状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    }
  }
}
</script>

